<!-- @module travel-form -->
<!-- @author: YunTao.Li -->
<!-- @description:  文件上传-->
<!-- @since: 2019-11-19 12:47:36 -->
<template>
  <div class="app-container">
    <fieldset class="fieldset" style="margin-top:5px;">
      <legend class="legend-font" v-text="grid_text_fileinfo" />
      <!-- form end -->
      <div class="div-body">
        <div class="div-button">
          <el-upload
            :action="uploadActionUrl"
            :before-upload="onBeforeUpload"
            :data="fileBizInfo"
            :on-progress="uploadFileProcess"
            :on-exceed="handleExceed"
            :on-error="uploadError"
            :show-file-list="false"
            :v-show="allowUpload"
            :headers="uploadHeaders"
            :on-success="uploadSuccess"
            :disable-upload-button="disableUploadButton"
            :disable-delete-button="disableDeleteButton"
            multiple
            :limit="100"
          >
            <el-button size="small" type="primary" :disabled="disableUploadButton">点击上传</el-button>
          </el-upload>
        </div>
        <!-- table begin-->
        <div class="div-table">
          <div :visible="processObject.progressVisible">
            <el-progress
              ref="progressRef"
              :text-inside="true"
              :stroke-width="15"
              :percentage="processObject.progressPercentage"
            />
          </div>
          <el-table :data="fileInfoList" border fit highlight-current-row style="width: 100%" max-height="450" size="mini">
            <!-- <el-table-column type="selection"  /> -->
            <el-table-column align="center" type="index" label="序号" />
            <!--文件真实名-->
            <el-table-column label="文件名" min-width="350px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.fileRealName }}</span>
              </template>
            </el-table-column>

            <!--附件类型-->
            <!-- <el-table-column label="附件类型"  align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.fileSuffixName }}</span>
              </template>
            </el-table-column> -->

            <!--附件大小-->
            <el-table-column label="附件大小" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.fileSize }}</span>
              </template>
            </el-table-column>

            <!--上传人-->
            <el-table-column label="上传人" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.createdBy }}</span>
              </template>
            </el-table-column>

            <!--上传时间-->
            <el-table-column label="上传时间" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.creationDate | parseTime('{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column width="200px" label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="small" type="danger" :disabled="disableDeleteButton" @click="handleDelete(scope.row)">删除</el-button>
                <el-button size="small" type="success" @click="handleDownload(scope.row)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
      <!-- table end -->
      <!-- <pagination v-show="total>0" :total="total" :page.sync="queryForm.page" :limit.sync="queryForm.limit" @pagination="getList" /> -->
      </div>
    </fieldset>
  </div>
</template>

<script>
// import Pagination from '@/components/Pagination'
import { getFileInfoList, fileDelete } from '@/api/file/file-service'
import axios from 'axios'
import Cookies from 'js-cookie'

export default {
  props: {
    paramPaDocId: {
      type: String,
      default: () => { return '' }
    },
    allowUpload: {
      type: Boolean,
      default: () => { return true }
    },
    disableUploadButton: {
      type: Boolean,
      default: () => { return false }
    },
    disableDeleteButton: {
      type: Boolean,
      default: () => { return false }
    }
  },
  // components: { Pagination },
  data() {
    return {
      grid_text_fileinfo: '文件上传',
      fileBizInfo: {
        paDocId: '',
        paType: '1r',
        createdBy: localStorage.getItem('empName')
      },
      processObject: {
        processTitle: '数据同步中，请耐心等待',
        progressPercentage: 0,
        progressVisible: false,
        progressColors: {
          percent20: '#f56c6c',
          percent50: '#6f7ad3',
          percent100: '#5cb87a'
        }
      },
      uploadHeaders: { Authorization: Cookies.get('Authorization') },
      fileInfoList: [],
      total: 0,
      queryForm: {
        page: 1,
        limit: 10,
        paDocId: ''
      },
      downloadActionUrl: process.env.VUE_APP_BASE_API + '/file/download',
      uploadActionUrl: process.env.VUE_APP_BASE_API + '/file/upload'
    }
  },
  watch: {
    paramPaDocId(val, oldVal) {
      if (val !== oldVal) {
        this.fileBizInfo.paDocId = val
        this.queryForm.paDocId = val
        this.onLoadFileInfos()
      }
    }
  },
  created() {
    this.fileBizInfo.paDocId = this.paramPaDocId
    this.queryForm.paDocId = this.paramPaDocId
    this.onLoadFileInfos()
  },
  methods: {
    onLoadFileInfos() {
      getFileInfoList(this.queryForm).then(response => {
        this.fileInfoList = response.data
      })
    },
    onBeforeUpload(file) { // 上传前验证
      const isLt1M = file.size / 1024 / 1024 < 1000000

      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!')
      }
      return isLt1M
    },
    handleExceed(files, fileList) { // 文件超出个数限制

    },
    handleDelete(item) {
      const fileId = item.fileId
      this.$confirm('确定要删除么?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        fileDelete(fileId).then(response => {
          if (response.code === 200) {
            this.$message({ type: 'success', message: '删除成功!' })
            this.onLoadFileInfos()
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(err => { console.error(err) })
    },
    handleDownload(item) {
      const param = `?fileId=${item.fileId}`
      const url = this.downloadActionUrl
      axios.post(url + param
        , { fileId: item.fileId }, { responseType: 'blob' })
        .then(response => {
          const data = response.data
          if (!data) {
            return
          }
          const contentDisposition = response.headers['content-disposition']
          const fileName = contentDisposition.substring(contentDisposition.indexOf('=') + 1)
          const url = window.URL.createObjectURL(new Blob([data]))
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = url
          a.setAttribute('download', fileName)
          document.body.appendChild(a)
          // 点击下载
          a.click()
          // 下载完成移除元素
          document.body.removeChild(a)
          // 释放掉blob对象
          window.URL.revokeObjectURL(url)
        }).catch(function(error) {
          console.log(error)
        })
    },
    uploadSuccess(response, file, fileList) { // 上传成功
      this.processObject.progressPercentage = 100
      this.onLoadFileInfos()
    },
    // eslint-disable-next-line handle-callback-err
    uploadError(err, file, fileList) { // 上传失败

    },
    uploadFileProcess(event, file, fileList) {
      this.fileArr = fileList
      var _this = this
      this.fileArr.forEach(item => {
        if (item.percentage === 100) {
          // do
          _this.processObject.progressPercentage = 100
        } else {
          _this.processObject.progressPercentage = Math.abs(item.percentage.toFixed(0))
        }
      })
    }
  }
}
</script>

<style>

</style>
